package org.zn.etl.jdbc;

import java.math.BigDecimal;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Types;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.apache.commons.lang3.tuple.Pair;

public class PreparedStatementTools {
	
	
	public static void setParamListByType(PreparedStatement ps,List<Pair<Integer, Object>> values) throws SQLException {
	
	}
	
	public static void setParamMapList(PreparedStatement ps,List<String>  names,Map<String, Object> row) throws SQLException {
		setParamList(ps,names.stream().map(it->  row.get(it)).collect(Collectors.toList()));
	}
	
	public static void setParamMapList(PreparedStatement ps,LinkedHashMap<String, Object> row) throws SQLException {
		setParamList(ps, row.values().stream().collect(Collectors.toList()));
	}
	
	
	public static void setParamList(PreparedStatement ps,List<Object> values) throws SQLException {
	
		for (int i = 0; i <values.size(); i++) {
			
			Object v=values.get(i);
			
			int ts=Types.VARCHAR;
			
			if (v instanceof String) {
				ts=Types.VARCHAR;
			} else if (v instanceof Integer) {
				ts=Types.INTEGER;
			} else if (v instanceof Long) {
				ts=Types.BIGINT;
			} else if (v instanceof Date) {
				ts=Types.DATE;
			} else if (v instanceof Double) {
				ts=Types.DOUBLE;
			} else if (v instanceof Boolean) {
				ts=Types.BOOLEAN;
			} else if (v instanceof Float) {
				ts=Types.FLOAT;
			} else if (v instanceof byte[]) {
				ts=Types.BLOB;
			} else if (v instanceof BigDecimal) {
				ts=Types.DECIMAL;
			}
			
			setParam(ps, i,v , ts);
			
		}

	}
	
	public static void setParam(PreparedStatement ps, int indx, Object value, int jdbcType) throws SQLException {

		if (TypeSets.STRING_TYPE_INT.contains(jdbcType)) {
			ps.setString(indx, (String) value);
		} else if (TypeSets.INT_TYPE_INT.contains(jdbcType)) {
			ps.setInt(indx, (Integer) value);
		} else if (TypeSets.DATA_TYPE_INT.contains(jdbcType)) {
			Date date = (Date) value;
			ps.setDate(indx, new java.sql.Date(date.getTime()));

		} else if (TypeSets.LONG_TYPE_INT.contains(jdbcType)) {
			ps.setLong(indx, (Long) value);
		} else if (TypeSets.DECIMA_LTYPE_INT.contains(jdbcType)) {
			ps.setBigDecimal(indx, (BigDecimal) value);
		} else if (TypeSets.BYTES_TYPE_INT.contains(jdbcType)) {
			ps.setBytes(indx, (byte[]) value);
		} else if (TypeSets.DOUBLE_TYPE_INT.contains(jdbcType)) {
			ps.setDouble(indx, (Double) value);
		} else if (TypeSets.BOOLEAN_TYPE_INT.contains(jdbcType)) {
			ps.setBoolean(indx, (Boolean) value);
		}

	}

}
